package com.qbccn.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.qbccn.blog.dto.ResponseCode;
import com.qbccn.blog.dto.ResponseResult;
import com.qbccn.blog.utils.OkhttpUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author linke
 * @date 2019-12-22 下午 22:44
 * @description
 */
@RestController
@RequestMapping("api")
public class ApiController {

    @Value("${security.oauth2.client.access-token-uri}")
    private String access_token_uri;
    @Value("${security.oauth2.client.client-id}")
    private String client_id;
    @Value("${security.oauth2.client.client-secret}")
    private String client_secret;
    private static final String grant_type = "password";

    @PostMapping("login")
    public ResponseResult login(String username, String password) {
        Map<String, String> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        map.put("grant_type", grant_type);
        map.put("client_secret", client_secret);
        map.put("client_id", client_id);
        String res = OkhttpUtils.post(access_token_uri, map);
        JSONObject jsonObject = JSONObject.parseObject(res);
        if (jsonObject.getString("access_token") != null) {
            return new ResponseResult(ResponseCode.OK, "登陆成功！", jsonObject);
        } else if (jsonObject.getString("error").equals("unauthorized")) {
            return new ResponseResult(ResponseCode.USER_NOT_EXIST, "账号不存在！");
        } else {
            return new ResponseResult(ResponseCode.PASSWORD_ERROR, "密码错误！");
        }
    }

}
